<script setup>
import { ref, watch } from "vue";
import { uniFetch } from '../../api/uni-fetch';
import { onReachBottom, onShow } from '@dcloudio/uni-app'
import ShoppingCartSkeleton from './components/ShoppingCartSkeleton.vue'
import { useUserStore } from "/store/user.js"
import customTabbar from '@/components/customTabbar/customTabbar.vue';
import { onShareAppMessage } from '@dcloudio/uni-app'

onShareAppMessage(() => {
	const openid = uni.getStorageSync("userLoginCode").openid || uni.getStorageSync("userLoginCode").user.openid
	return {
		title: '华靓甄选-购物车',
		path: '/pages/ShoppingCart/ShoppingCart?invite_token=' + openid
	}
})

const cartList = ref([])
const store = useUserStore()
// TODO 获取购物车列表哦
let page = 1
let total = 0
const isLoading = ref(false)
async function getCartList() {
	const res = await uniFetch.post('/shop-cart/list', { app_id: uni.appId, page, pageSize: 4 })
	console.log(res, '购物车列表');
	if (res.code !== 10000) {
		return uni.showToast({ title: '获取列表错误', icon: 'none' })
	}
	isLoading.value = true
	cartList.value.push(...res.data.list)
	total = res.data.total
}
onShow(() => {
	if (!store.token) {
		uni.showToast({ title: '您未登录', icon: 'none' })
		isLoading.value = true
		return
	}

	page = 1
	isLoading.value = false
	cartList.value = []
	getCartList()
})

onReachBottom(() => {
	if (total > cartList.value.length) {
		page++
		getCartList()
		console.log('page++');
	}
	console.log('触底');
})


const totolCount = ref(0)
const totolMoney = ref(0)

const isALL = ref(false)
watch(() => cartList, (newPerson, oldPerson) => {
	isALL.value = cartList.value.every(item => item.checked)
	totolCount.value = 0
	totolMoney.value = 0
	cartList.value.forEach(item => {
		if (item.checked) {
			console.log(item.num);
			totolCount.value += item.count
			if (store.memberInfo.is_member){
				totolMoney.value += (item.count * floatNum(item.member_price))
			} else {
				totolMoney.value += (item.count * floatNum(item.product.price))
			}

		}
	})

}, {
	deep: true
})


// 选择商品
function chooseGoods(event, index) {
	console.log(event);
	cartList.value[index].checked = !cartList.value[index].checked
	isALL.value = cartList.value.every(item => item.checked)

}

// 全选
function allNo() {
	isALL.value = !isALL.value
	for (let i = 0; i < cartList.value.length; i++) {
		cartList.value[i].checked = isALL.value
	}
}


function floatNum(num) {
	let float = num.toFixed(2)
	float = float * 100
	float = float + ''
	console.log(float);
	console.log(typeof float)
	const inte = float.split('.')[0]
	return inte
}

// 去支付
function goPayment() {
	if (totolCount.value == 0) {
		return uni.showToast({
			title: '请选择商品',
			icon: 'none'
		})
	}

	let arr = []
	cartList.value.forEach(item => {
		item.checked ? arr.push({ ids: item.id, count: item.count, goodsId: item.product.id }) : arr
	})
	let str = JSON.stringify(arr)
	uni.navigateTo({
		url: '/subpkg/CreatOrder/CreatOrder?arr=' + str
	})
}

// 删除
const isDelete = ref(false)
async function deleteItem() {
	let ids = ''
	cartList.value.forEach(item => {
		item.checked ? ids += item.id + ',' : ids
	})
	console.log(ids, 'ids');


	const res = await uniFetch.post('/shop-cart/delete',
		{ ids, app_id: uni.appId })
	console.log(res, '删除产品');
	if (res.code === 10000) {
		cartList.value = cartList.value.filter(item => !item.checked)
	}

	isDelete.value = false
}

// 购物车数量增加
async function addCount($event, info) {
	console.log($event, info, '失去焦点info');
	let num = $event.value - info.count
	if (num === 0) return
	const res = await uniFetch.post('/shop-cart/add', {
		product_id: info.product.id,
		count: num,
		app_id: uni.appId
	})
	console.log(res);
	if (res.code === 10000) {
		console.log('成功');
		cartList.value.forEach(item => {
			if (item.id === info.id) {
				item.count = $event.value
				return
			}
		})
	} else {
		uni.showToast({
			title: res.msg,
			icon: 'none'
		})
	}
}
</script>


<template>
	<view class="container" v-if="isLoading">
		<!-- 页面顶部 -->
		<view class="head-info">
			<view class="cart-total">
				库存有限，请快速下单
			</view>
			<view class="cart-edit">
				<view class="normal" v-if="!isDelete" @click="isDelete = true">
					<text class="icon iconfont icon-bianji"></text>
					<text>编辑</text>
				</view>
				<view class="edit" v-else @click="deleteItem">
					<text>删除</text>
				</view>
			</view>
		</view>
		<!-- 购物车商品列表 -->
		<view class="cart-list">
			<view class="cart-item" v-for="(item, index) in cartList" :key="item.id">
				<label class="item-radio">
					<radio class="radio" color="#f92f01" :checked="item.checked" @click="chooseGoods(item, index)" />
				</label>
				<view class="goods-image">
					<image class="image" :src="item?.image" mode="x"></image>
				</view>
				<view class="item-content">
					<view class="goods-title">
						<text class="twoline-hide">{{ item.product?.title }}</text>
					</view>
					<view class="goods-props clearfix">
						<view class="goods-props-item">
							<text>{{ item.product?.sub_title }}</text>
						</view>
					</view>
					<view class="item-foot">
						<view class="goods-price">
							<view class="value" v-if="store.memberInfo.is_member">￥{{ item.member_price?.toFixed(2) }}
							</view>
							<view class="value" v-else>￥{{ item.product.price.toFixed(2) }}</view>
							<view class="unit">￥{{ item.product?.old_price.toFixed(2) }}</view>

						</view>
						<view class="stepper">
							<u-number-box :min="1" v-model="item.count" integer :step="1" :asyncChange="true"
								@blur="addCount($event, item)" @change="addCount($event, item)"></u-number-box>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 购物车数据为空 -->
		<Empty tips="购物车是空的" v-if="!cartList.length"></Empty>
		<!-- 底部操作栏 -->
		<view class="footer-fixed">
			<label class="all-radio">
				<radio class="radio" color="#f92f01" :checked="isALL" @click="allNo" />
				<text>全选</text>
			</label>
			<view class="total-info">
				<text>合计：</text>
				<view class="goods-price">
					<text class="unit">￥</text>
					<text class="value">{{ totolMoney / 100 }}</text>
				</view>
			</view>
			<view class="cart-action">
				<view class="btn-wrapper">
					<view class="btn-item btn-main" :class="{ disabled: !totolCount > 0 }" @click="goPayment">
						<text>去结算 {{ totolCount }} </text>
					</view>
					<!-- <view  class="btn-item btn-main disabled" >
            <text>删除</text>
          </view> -->
				</view>
			</view>
		</view>

		<!-- <view class="safe-area"></view> -->
	</view>

	<ShoppingCartSkeleton v-else></ShoppingCartSkeleton>
	<!-- <customTabbar></customTabbar> -->
</template>


<style>
page {
	background: #f5f5f5;
}
</style>
<style lang="scss">
@import "/uni.scss";
.safe-area {
  height: calc(env(safe-area-inset-bottom) + 110rpx);
  background: #fff;
}
// 页面顶部
.head-info {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 4rpx 30rpx;
	margin-bottom: 30rpx;
	background-color: #fff;
	height: 80rpx;

	.cart-total {
		font-size: 28rpx;
		color: #333;
	}

	.cart-edit {
		padding-left: 20rpx;

		.icon {
			margin-right: 12rpx;
		}

		.edit {
			color: #fa2209;
		}
	}

}

// 购物车列表
.cart-list {
	padding: 0 16rpx 110rpx 16rpx;
}

.cart-item {
	background: #fff;
	border-radius: 12rpx;
	display: flex;
	align-items: center;
	padding: 30rpx 10rpx;
	margin-bottom: 24rpx;


	.item-radio {
		width: 40rpx;
		line-height: 80rpx;
		margin-right: 10rpx;
		text-align: center;

		.radio {
			transform: scale(0.76)
		}
	}

	.goods-image {
		width: 200rpx;
		height: 200rpx;

		.image {
			display: block;
			width: 100%;
			height: 100%;
			border-radius: 8rpx;
		}
	}

	.item-content {
		flex: 1;
		padding-left: 24rpx;

		.goods-title {
			font-size: 28rpx;
			max-height: 76rpx;

			.twoline-hide {
				display: -webkit-box;
				-webkit-line-clamp: 2;
				-webkit-box-orient: vertical;
				overflow: hidden;
				text-overflow: ellipsis;
			}
		}

		.goods-props {
			margin-top: 14rpx;
			height: 40rpx;
			color: #ababab;
			font-size: 24rpx;
			overflow: hidden;

			.goods-props-item {
				display: inline-block;
				margin-right: 14rpx;
				padding: 4rpx 16rpx;
				border-radius: 12rpx;
				background-color: #F5F5F5;
				max-width: 200rpx;
				overflow: hidden;
				white-space: nowrap;
				text-overflow: ellipsis;
			}
		}


		.item-foot {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-top: 20rpx;

			.goods-price {
				vertical-align: bottom;

				.unit {
					font-size: 24rpx;
					color: #ababab;
					text-decoration: line-through;
				}

				.value {
					color: $custom-theme-red;
					font-size: 35rpx;
				}
			}
		}

	}
}

// 空数据按钮
.empty-ipt {
	width: 220rpx;
	margin: 0 auto;
	font-size: 32rpx;
	height: 64rpx;
	line-height: 64rpx;
	text-align: center;
	color: #fff;
	border-radius: 50rpx;
	background: generate-gradient($custom-theme-color, $custom-theme-color-l);
}

// 底部操作栏
.footer-fixed {
	display: flex;
	align-items: center;
	height: 96rpx;
	background: #fff;
	padding: 0 30rpx;
	position: fixed;
	// bottom: calc(env(safe-area-inset-bottom) + 100rpx);;
	bottom: 0;
	left: 0;
	right: 0;
	z-index: 11;

	.all-radio {
		width: 160rpx;
		display: flex;
		align-items: center;

		.radio {
			margin-bottom: -4rpx;
			transform: scale(0.76)
		}
	}

	.total-info {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: flex-end;
		padding-right: 30rpx;

		.goods-price {
			vertical-align: bottom;
			color: #fa2209;

			.unit {
				font-size: 24rpx;
			}

			.value {
				font-size: 32rpx;
			}
		}
	}

	.cart-action {
		width: 200rpx;

		.btn-wrapper {
			height: 100%;
			display: flex;
			align-items: center;
		}

		.btn-item {
			flex: 1;
			font-size: 28rpx;
			height: 72rpx;
			line-height: 72rpx;
			text-align: center;
			color: #fff;
			border-radius: 50rpx;
		}

		// 立即购买按钮
		.btn-main {
			background: generate-gradient(#3bae43, #a0d59b);

			// 禁用按钮
			&.disabled {
				opacity: 0.6;
			}
		}

	}

}
</style>